package com.nbcio.pm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.common.core.utils.MapstructUtils;
import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.pm.domain.PmProject;
import com.nbcio.pm.domain.bo.PmProjectBo;
import com.nbcio.pm.domain.vo.PmProjectVo;
import com.nbcio.pm.mapper.PmProjectMapper;
import com.nbcio.pm.service.IPmProjectService;
import com.nbcio.pm.service.impl.PmProjectValidationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 项目管理Service业务层处理
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmProjectServiceImpl implements IPmProjectService {

    private final PmProjectMapper baseMapper;
    private final PmProjectValidationService validationService;

    /**
     * 查询项目列表
     */
    @Override
    public TableDataInfo<PmProjectVo> queryPageList(PmProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PmProject> lqw = buildQueryWrapper(bo);
        Page<PmProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询项目详细信息
     */
    @Override
    public PmProjectVo queryById(Long projectId) {
        return baseMapper.selectPmProjectById(projectId);
    }

    /**
     * 新增项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PmProjectBo bo) {
        PmProject add = MapstructUtils.convert(bo, PmProject.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setProjectId(add.getProjectId());
        }
        return flag;
    }

    /**
     * 修改项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(PmProjectBo bo) {
        PmProject update = MapstructUtils.convert(bo, PmProject.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 删除项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 更新项目进度
     */
    @Override
    public Boolean updateProgress(Long projectId, BigDecimal progress) {
        return baseMapper.updateProjectProgress(projectId, progress) > 0;
    }

    /**
     * 获取项目统计信息
     */
    @Override
    public PmProjectVo getProjectStats(Long projectId) {
        return baseMapper.selectProjectStats(projectId);
    }

    /**
     * 获取用户参与的项目列表
     */
    @Override
    public List<PmProjectVo> getUserProjects(Long userId) {
        return baseMapper.selectUserProjects(userId);
    }

    /**
     * 复制项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyProject(Long projectId, String newProjectName) {
        PmProjectVo originalProject = baseMapper.selectPmProjectById(projectId);
        if (originalProject == null) {
            return false;
        }

        PmProject newProject = MapstructUtils.convert(originalProject, PmProject.class);
        newProject.setProjectId(null);
        newProject.setProjectName(newProjectName);
        newProject.setProjectCode(generateProjectCode());
        newProject.setStatus("planning");
        newProject.setProgress(BigDecimal.ZERO);
        newProject.setActualStartDate(null);
        newProject.setActualEndDate(null);
        newProject.setActualCost(BigDecimal.ZERO);

        return baseMapper.insert(newProject) > 0;
    }

    /**
     * 归档项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean archiveProject(Long projectId) {
        PmProject project = new PmProject();
        project.setProjectId(projectId);
        project.setStatus("completed");
        return baseMapper.updateById(project) > 0;
    }

    private LambdaQueryWrapper<PmProject> buildQueryWrapper(PmProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmProject> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), PmProject::getProjectName, bo.getProjectName());
        lqw.like(StringUtils.isNotBlank(bo.getProjectCode()), PmProject::getProjectCode, bo.getProjectCode());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PmProject::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getPriority()), PmProject::getPriority, bo.getPriority());
        lqw.eq(bo.getManagerId() != null, PmProject::getManagerId, bo.getManagerId());
        lqw.eq(bo.getClientId() != null, PmProject::getClientId, bo.getClientId());
        lqw.eq(bo.getIsTemplate() != null, PmProject::getIsTemplate, bo.getIsTemplate());
        lqw.eq(bo.getIsPublic() != null, PmProject::getIsPublic, bo.getIsPublic());
        
        // 安全地处理params，避免空指针异常
        if (params != null) {
            lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                    PmProject::getCreateTime, params.get("beginTime"), params.get("endTime"));
        }
        
        lqw.orderByDesc(PmProject::getCreateTime);
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmProject entity) {
        // TODO 做一些数据校验,如唯一约束
        
        // 验证项目经理是否为项目成员（仅在更新时验证，新增时项目经理可能还未加入项目）
        if (entity.getProjectId() != null && entity.getManagerId() != null) {
            if (!validationService.validateProjectManager(entity.getProjectId(), entity.getManagerId())) {
                log.warn("项目经理 {} 不是项目 {} 的成员", entity.getManagerId(), entity.getProjectId());
                // 这里可以选择抛出异常或仅记录警告
                // throw new ServiceException("项目经理必须是项目成员");
            }
        }
    }

    /**
     * 生成项目编码
     */
    private String generateProjectCode() {
        return "PRJ" + System.currentTimeMillis();
    }
}
